﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Serialize.Library;
using System;

namespace Message.Library.Aliyun
{
    public  class AliyunSendMsg
    {

        /// <summary>
        /// 获取配置信息
        /// </summary>
        public  AliyunConfig Config
        {
            get { return ConfigManager.config; }
        }


        /// <summary>
        /// 发送短信共用方法  1发送成功  2手机号码不正确 3发送失败
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static　int SendMessage<T>(MessageInfo<T> message)
        {
            if (string.IsNullOrEmpty(message.Mobile))
            {
                return 2;
            }
            var config = ConfigManager.config; ;

            string product = "Dysmsapi";//短信API产品名称
            string domain = "dysmsapi.aliyuncs.com";//短信API产品域名
            string accessKeyId = config.AccessKeyId;//你的accessKeyId
            string accessKeySecret = config.AccessKeySecret;//你的accessKeySecret

            //服务器节点
            string endPoint = config.Endpoint;
            if (string.IsNullOrEmpty(endPoint))
                endPoint = "cn-hangzhou";

            IClientProfile profile = DefaultProfile.GetProfile(endPoint, accessKeyId, accessKeySecret);

            DefaultProfile defaultProfile =  DefaultProfile.GetProfile(endPoint, accessKeyId, accessKeySecret);
            defaultProfile.AddEndpoint(endPoint, endPoint, product, domain);

            IAcsClient acsClient = new DefaultAcsClient(profile);

            SendSmsRequest request = new SendSmsRequest();
            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = message.Mobile;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = config.SignName;
                //必填:短信模板-可在短信控制台中找到
                //request.TemplateCode = message.templateCode;
                request.TemplateCode = config.TemplateCode[$"{message.TemplateCodeKey}"];
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam =  message.Message.ToJson();
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                //request.OutId = "21212121211";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);

                if (sendSmsResponse.Code != "OK")
                {
                    return 3;
                }
                return 1;
            }
            catch (ServerException ex)
            {
                throw ex;
            }
            catch (ClientException ex)
            {
                throw ex;
            }
        }
    }
}
